<?php

class Base extends Zend_Db_Table{  
    protected $_db;
    protected $_table;
	protected $_exe;
    public function __construct() {
    	
		parent::__construct();
		$this->_db = $this->getAdapter();
		$dbConfig = $this->_db->getConfig();
		$count=strpos(get_called_class(),"Model"); 
		$str=substr_replace(get_called_class(),"",$count); 
		$this->_table = $dbConfig['prefix'].strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str));
		$this->_exe = $this->_db->select();
		$this->_exe->from($this->_table);
    }   
	
    function where($where){
        $where = (array) $where;

        foreach ($where as $key => $val) {
            // is $key an int?
            if (is_int($key)) {
                // $val is the full condition
                $this->_exe->where($val);
            } else {
                // $key is the condition with placeholder,
                // and $val is quoted into the condition
                $this->_exe->where($key, $val);
            }
        }

        return $this->_exe;
    }
	
	function limit($count,$offsite){
		$this->_exe->limit($count,$offsite);
		return $this->_exe;
	}
	
	function limitPage($page, $rowCount){
		$this->_exe->limitPage($page, $rowCount);
		return $this->_exe;
	}
	
	function order($order = ''){
		$this->_exe->order($order);
	}
	
	function select($format = false){
		return $this->_db->fetchAll($this->_exe);
	}

	function fetch($format = false){
		return $this->_db->fetchRow($this->_exe);
	}
	
	public function save($data = [], $where = []){
		
		$res=$this->_db->update($this->_table,$data,$where);
		return $res;
		
	}
	
	public function add($data = []){
		
		$this->_db->insert($this->_table,$data);
		return  $this->_db->lastInsertId();
		
	}
	
	public function delete($where = []){
		return $this->_db->delete($this->_table,$where);
	}
	
	public function count($where=[]){
		$this->_db = $this->getAdapter();
		$this->_exe = $this->_db->select();
		$this->_exe->from($this->_table, "count(*) as totalnumber");
		if($where){
			foreach ($where as $key => $val) {
				if (is_int($key)) {
				   
				   $this->_exe->where($val);
				} else {
				  
					$this->_exe->where($key, $val);
				}
			}   
		}
		
		$rs = $this->_db->fetchRow($this->_exe);
		
		return $rs['totalnumber'];
		
	}
	
	public function join($alias = '', $condition = '',$cols = '*'){
		
		$this->_exe->join($alias, $condition, $cols);
		
	}
	
	public function getList($where = [], $page= 0, $pagesize= 10){
		
		if($where) $this->where($where);
		
		if($pagesize) $this->limitPage($page, $pagesize);
		
		
		return $this->select();
	}
	
	public function getOne($where = []){
		
		//$where['id = ?'] = 1;
		if($where) $this->where($where);
		
		return $this->fetch();
	}
 
}
